<template>
  <div class="app-container">
    <!-- <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="handleResetClick" /> -->
    <PageContent ref="contentRef" :gridOptions="gridOptions" :content-config="contentConfig" @addClick="addClick" @edit-click="handleEditClick"
      @export-click="handleExportClick" >
      <template #status="scope">
        <!-- :type="statusList[scope.row[scope.prop]].type" -->
        <el-tag type="success" v-if="scope.row[scope.prop] === 'active'">
          {{ t('status.48') }}
        </el-tag>
        <el-tag type="danger" v-else>
          {{ t('status.49') }}
        </el-tag>
      </template>
      <template #type="scope">
        <!-- :type="statusList[scope.row[scope.prop]].type" -->
        <el-tag :type="typeList[scope.row[scope.prop]].type">
          {{typeList[scope.row[scope.prop]].label }}
        </el-tag>
      </template>
      <template #payment_provider_id="scope">
        <!-- :type="statusList[scope.row[scope.prop]].type" -->
        <el-tag>
          {{ getIdToPro(scope.row[scope.prop])?.name || '--'}}
        </el-tag>
      </template>

      <template #tool="scope">
        <!-- <template v-if="[0,2].includes(scope.row.status)">
          <el-button size="small" type="primary" link @click="toolClick('approve',scope)">
            {{$t('oper.4')}}
          </el-button>
          <el-button size="small" type="primary" link @click="toolClick('deny',scope)">
            {{$t('oper.5')}}
          </el-button>
        </template> -->
      </template>
    </PageContent>

    <el-dialog v-model="dialogVisible" width="900" :close-on-click-modal="false" @close="closeDialog" align-center>
      <!-- 表单 -->
      <el-form ref="formRef" class="max-h-80vh overflow-auto w-full px-5" :model="formData" :rules="formRules" label-width="120px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('label.39')" prop="payment_provider_id">
            <el-select v-model="formData.payment_provider_id" :placeholder="$t('hint.19')"
              @change="selectChange('payment_provider_id')">
              <template v-for="option in providersList" :key="option.id">
                <el-option :label="option.name" :value="option.id" />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('label.102')" prop="type">
            <el-select v-model="formData.type" :placeholder="$t('hint.110')" @change="selectChange('type')">
              <template v-for="(option,index) in typeList" :key="option.value">
                <el-option :label="option.label" :value="index" />
              </template>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('label.23')" prop="status">
            <el-select v-model="formData.status" :placeholder="$t('hint.150')" @change="selectChange('type')">
              <el-option :label="t('status.48')" value="active" />
              <el-option :label="t('status.49')" value="inactive" />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('label.53')" prop="currency_code">
            <el-select v-model="formData.currency_code" :placeholder="$t('hint.111')"
              @change="selectChange('currency_code')">
              <template v-for="option in currList" :key="option.currency_code">
                <el-option :label="option.currency_code" :value="option.currency_code" />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('label.92')" prop="name">
            <el-input v-model="formData.name" :placeholder="$t('hint.118')" />
          </el-form-item>
          <!-- <el-form-item :label="$t('label.101')" prop="name">
            <el-select v-model="formData.name" :placeholder="$t('hint.112')" @change="selectChange('name')">
              <template v-for="option in channelsList" :key="option.name">
                <el-option :label="option.name" :value="option.name" />
              </template>
            </el-select>
          </el-form-item> -->
          <el-form-item :label="item.label" :prop="`${item.pKey}.${item.key}`" v-for="item in appItem" :key="item.key"
            :rules="item.rules">
            <!-- <template #label>
              <div class="flex-inline items-center">
                <span class="truncate  pl-5px">{{item.label}}</span>
              </div>
            </template> -->
            <template v-if="item.type==='select'">
              <el-select v-model="formData[item.pKey][item.key]" :placeholder="item.placeholder">
                <template v-for="option in item.options" :key="option.name">
                  <el-option :label="option.name" :value="option.name" />
                </template>
              </el-select>
            </template>
            <template v-else>
              <el-input v-model="formData[item.pKey][item.key]" :type="item.type" :placeholder="item.placeholder" />
            </template>
          </el-form-item>
          <el-form-item :label="$t('form.12')" prop="sort">
            <el-input v-model="formData.sort" :placeholder="$t('hint.24')" />
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="t('label.170')" prop="extra">
              <div v-for="(item, index) in formData.extra" :key="index" class="flex flex-row justify-between items-center gap-5 mb-2">
                <el-input v-model="item.name"  :placeholder="t('label.key')" />
                <el-input v-model="item.label" :placeholder="t('label.value')" />
                <el-button type="danger" :icon="Delete" @click="removeExtra(index)" />
              </div>
              <el-button type="primary" :icon="Plus" @click="ddExtra">{{ t('label.171') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{$t('btn.1')}}
          </el-button>
          <el-button @click="closeDialog">
            {{$t('btn.8')}}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import searchConfig from "./config/search";
import contentConfig from "./config/content";
import usePage from "@/hooks/usePage";
import { onMounted } from "vue";
import { tableHeightAutoAdjust } from '@/utils/common'
import Api from '@/api/payment/payMethods'
import { Plus, Delete } from "@element-plus/icons-vue";
defineOptions({
  name: "paymentPayMethods",
  inheritAttrs: false,
});
const { t } = useI18n();

const gridOptions = reactive({})

const { searchRef, contentRef, addModalRef, editModalRef,
  handleQueryClick, handleResetClick, handleAddClick,
  handleSubmitClick, handleExportClick, } = usePage();

const formData = ref({
  id:"",
  payment_provider_id: "",
  type: "deposit",
  status:"",
  currency_code: "",
  name: '',
  config: {},
  secret_config: {},
  sort:0,
  extra:[],
})

// 点击新增操作
const addClick = () => {
  dialogVisible.value = true
  // appendsArr.value = []
  // formData.value = {}
  // handleAddClick()
}
// 编辑
const handleEditClick = (row) => {
  console.log('row===>', row)
  for (let key in formData.value) {
    // 如果row['extra']不存在，则赋值默认空数组
    if(key === 'extra' && !row[key]) {
      formData.value[key] = []
    } else {
      formData.value[key] = row[key];
    }
  }
  dialogVisible.value = true
  getCurr()
  getChannels()
  getAppRules(row.payment_provider_id)
}
const formRef = ref(null)
const typeList = {
  deposit: { label: t('status.deposit'), value: "deposit", type: "primary" },
  withdrawal: { label: t('status.withdrawal'), value: "withdrawal", type: "danger" }
}

const formRules = ref({
  payment_provider_id: [{ required: true, message: t('hint.19'), trigger: "change" }],
  type: [{ required: true, message: t('hint.110'), trigger: "change" }],
  status: [{ required: true, message: t('hint.150'), trigger: "change" }],
  currency_code: [{ required: true, message: t('hint.111'), trigger: "change" }],
  name: [{ required: true, message: t('hint.112'), trigger: "change" }],
  sort:[{ required: true, message: t('hint.24'), trigger: "blur" }]
})
const appItem = ref([])
const getAppRules = (id) => {
  const data = getIdToPro(id)
  console.log('appItem====>',data);
  const types = formData.value.type === 'deposit' ? 'deposit' : 'withdrawal'
  const config = data[`${types}_config`]
  const secret_config = data[`${types}_secret_config`]
  appItem.value = []
  if (!formData.value.id) {
    formData.value.config = {}
  }
  formData.value.secret_config = {}
  for (let i in config) {
    const item = config[i]
    appItem.value.push({
      label: item.label,
      type: item.type,
      element: item.element,
      options: item.options || [],
      placeholder: item.default || `${t('hint.109')}${item.label}`,
      key: item.name,
      pKey: 'config',
      rules: { required: true, message: `${t('hint.109')}${item.label}`, trigger: 'blur' }
    })
    formData.value.config[item.name] = formData.value.config[item.name] || item.default || ''
  }
  for (let i in secret_config) {
    const item = secret_config[i]
    appItem.value.push({
      label: item.label,
      type: item.type,
      element: item.element,
      options: item.options || [],
      placeholder: item.default || `${t('hint.109')}${item.label}`,
      pKey: 'secret_config',
      key: item.name,
      // rules: { required: true, message: `${t('hint.109')}${item.label}`, trigger: 'blur' }
    })
    formData.value.secret_config[item.name] = item.default || ''
  }
}
const dialogVisible = ref(false)

const loading = ref(false)
const closeDialog = () => {
  formData.value = {
    payment_provider_id: "",
    type: "deposit",
    status:"",
    currency_code: "",
    name: '',
    config: {},
    secret_config: {},
    sort:0,
    extra:[]
  }
  formRef.value.clearValidate()
  appItem.value = []
  dialogVisible.value = false
}
const handleSubmit = () => {
 
  formRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      console.log('提交=====>',formData.value)
      if (formData.value.id) {
        Api.put(formData.value).then((s) => {
          ElMessage.success(t("hint.107"))
          handleSubmitClick()
          closeDialog()
        }).finally(() => {
          loading.value = false
        })
      } else {
        Api.add(formData.value).then((s) => {
          ElMessage.success(t("hint.108"))
          handleQueryClick()
          closeDialog()
        }).finally(() => {
          loading.value = false
        })
      }
    }
  })
}
const selectChange = (key) => {
  const keys = ['payment_provider_id', 'type', 'currency_code']
  if (key === 'payment_provider_id') {
    formData.value.currency_code = ''
    currList.value = []
    getCurr()
  } else if (key === 'name') {
    return false
  }
  if (key === 'payment_provider_id' || key === 'type') {
    getAppRules(formData.value.payment_provider_id)
  }
  for (let i in keys) {
    if (!formData.value[keys[i]]) {
      return false
    }
  }
  formData.value.name = ''
  getChannels()
}
const currList = ref([])
const getCurr = async () => {
  const { data } = await Api.getCurr({ payment_provider_id: formData.value.payment_provider_id })
  currList.value = data
}
const channelsList = ref([])
const getChannels = async () => {
  const { data } = await Api.getChannels({
    payment_provider_id: formData.value.payment_provider_id,
    currency_code: formData.value.currency_code,
    type: formData.value.type === 'deposit' ? 'deposit' : 'withdrawal',
  })
  channelsList.value = data
}
const providersList = ref([])
const getIdToPro = (id) => {
  return providersList.value.find(item => item.id == id)
}
const getProviders = async () => {
  const { data } = await Api.providers()
  providersList.value = data
}

function ddExtra() {
  formData.value.extra.push({ name: "", label: "" });
}

function removeExtra(index) {
  formData.value.extra.splice(index, 1);
}
onMounted(() => {
  getProviders()
  // 确保在组件挂载后立即设置高度
  tableHeightAutoAdjust(gridOptions);
})
</script>

<style></style>